import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import {
	login
} from '@/api/user.js'

// 安装 Vuex 插件
Vue.use(Vuex);

// 创建 Vuex Store
export default new Vuex.Store({
	state: {
		tokenInfo: null,
		// 定义全局状态
		wxUserInfo: null, //微信用户信息
		user: null, // 用户信息
	},
	mutations: {
		setUser(state, user) {
			state.user = user;
		},
		setWxUserInfo(state, info) {
			state.wxUserInfo = info;
		},
		setTokenInfo(state, tokenInfo) {
			state.tokenInfo = tokenInfo;
		}
	},
	actions: {
		login(context, data) {
			console.log("传递了吗", data);
			// code: res.code,
			// 	userInfo: context.state.wxUserInfo,
			// 	iv:data.userInfo.iv,
			// 	encryptedData:data.userInfo.encryptedData
			wx.login({
				success: (res) => {
					if (res.code) {
						login({
							code: res.code,
							phoneCode:{
								code: data.phoneCode.code,
								iv:data.phoneCode.iv,
								encryptedData:data.phoneCode.encryptedData
							}
						}).then(res => {
							console.log("拿到了手机号",res.data)
							uni.navigateBack();
							const token = res.data.token;
							const expires_in = 14400; //4小时
							const expires_at = Date.now() + (expires_in * 1000); // 计算过期时间
							let tokenData = {
								"token": token,
								"expires_at": expires_at
							}
							this.commit('setTokenInfo', tokenData);
							this.commit('setUser', res.data);
						}).catch(err => {
							console.error(err)
						})
					} else {
						console.error('登录失败！' + res.errMsg)
					}
				}
			})
		}
	},
	getters: {
		user(state) {
			return state.user;
		},
		userName(state) {
			return state.user ? state.user.username : '';
		},
		wxUserInfo(state) {
			return state.wxUserInfo;
		}
	},
	plugins: [
		createPersistedState({
			storage: {
				getItem: key => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: key => uni.removeStorageSync(key)
			}, // 使用 uni-app 的存储方法
			paths: ['user', 'tokenInfo'] // 持久化的状态路径
		})
	]
});
